package cn.yesway.springioc.reflect;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
/***
 * 在访问private、protected成员变量和方法时必须通过setAccessible(boolean access)方法取消Java语言检查，否则将抛出IllegalAccessException。
 * 如果JVM的安全管理器设置了相应的安全机制，调用该方法将抛出SecurityException。 
 * @comment:
 * @author chencq
 * @Email:hero901027@163.com
 */
public class PrivateCarReflectTest {
   public static void main(String[] args) throws Throwable {
	   PrivateCarReflectTest test=new PrivateCarReflectTest();
       test.test1();
       test.test2();
   }
   
   public  void  test1() throws Throwable{
	   ClassLoader loader = Thread.currentThread().getContextClassLoader();
	   Class clazz = loader.loadClass("cn.yesway.springioc.reflect.PrivateCar");
	   PrivateCar pcar = (PrivateCar)clazz.newInstance();
	   
	   Field colorFld = clazz.getDeclaredField("color");
        //①取消Java语言访问检查以访问private变量
	   colorFld.setAccessible(true); 
	   colorFld.set(pcar,"红色");
	   
	   Method driveMtd = clazz.getDeclaredMethod("drive",(Class[])null);
        //Method driveMtd = clazz.getDeclaredMethod("drive"); JDK5.0下使用
       
        //②取消Java语言访问检查以访问protected方法
	   driveMtd.setAccessible(true); 
        driveMtd.invoke(pcar,(Object[])null);
   }
   
   public  void  test2() throws Exception{
	   PrivateCar pcar =(PrivateCar) ClassReflectUtil.getInstance("cn.yesway.springioc.reflect.PrivateCar");
	   ClassReflectUtil.setFieldValue(pcar, "color","红色");
	   ClassReflectUtil.executeMethod(pcar, "drive", null, null);
   }
}